<?php
//app/Controller/IssuesController.php
class IssuesController extends AppController
{
    public function index()
    {
    	$issues = $this->Issue->find('all');
        $this->set(array(
            'issues' => $issues,
            '_serialize' => array('issues')
        ));
    }
	
	public function view($id)
	{
		$issue = $this->Issue->findById($id);
		if($issue) {
			$this->set(array(
				'issue' => $issue,
            	'_serialize' => array('issue')
			));
		} else {
        	$this->response->statusCode(404);
			$this->autoRender = false;
		}
	}
	
	public function add()
	{
        if ($this->Issue->save($this->request->data)) {
			$location = $this->request->base . '/issues/' . $this->Issue->id;
			if($this->RequestHandler->ext) {
				$location .=  '.' . $this->RequestHandler->ext;
			}
			
			$this->response->header('Content-Location', $location);
        	$this->response->statusCode(201);
        } else {
        	$this->response->statusCode(500);
        }
		$this->autoRender = false;
	}
	
	public function edit($id)
	{
		$this->Issue->id = $id;
		
		$count = $this->Issue->find('count', array('conditions' => array('Issue.id' => $id)));
		if($count == 0) {
			$this->response->statusCode(404);
		} else if ($this->Issue->save($this->request->data)) {
			// Get the updated copy
			$issue = $this->Issue->findById($id);
			$this->set(array(
				'issue' => $issue,
            	'_serialize' => array('issue')
			));
        	$this->render('view');
		} else {
        	$this->response->statusCode(500);
		}
		$this->autoRender = false;
	}
	
	public function delete($id)
	{
		$count = $this->Issue->find('count', array('conditions' => array('Issue.id' => $id)));
		if($count == 0) {
			$this->response->statusCode(404);
		} else if($this->Issue->delete($id)) {
			$this->response->statusCode(204);
		} else {
			$this->response->statusCode(500);
		}
		$this->autoRender = false;
	}
}